/* eslint-disable no-param-reassign */
/* eslint-disable array-callback-return */
/* eslint-disable consistent-return */
import { message } from 'antd';
import {
  getDictCode,
  getAreaList,
  getCustList,
  getConfigList,
  getCustAllList,
  getSendOrderCustList,
  getSupplyList,
  getNsSupplyList,
  getBillSupplyList,
  getContList,
  getSuppContList,
  getQuoList,
  getSendRecvSuppList,
  getEmpNameList,
  getFileName,
  getProType,
  signPro,
  getProList,
  getServiceType,
  getCustEsOsList,
  uploadFile,
  getServiceDictList,
  getNsCustList,
  fetchAssoCustomer,
  getQuoInfo,
  getInsDetailInfo,
  fetchInjRatioPage,
  getDetailInforPage,
  getAccuDetailInfo,
  getDetailAccuPage,
  getJoinIdeList,
  getInsDetailData,
  getPdIdDetailData,
  getAccuDetailData,
  getAccuLsPkgDetailData,
  getInjSecAccoDetailData,
  getEsOnceCustList,
  getIdCodeEmpList,
  getEsPersonList,
  getOsAccoList,
} from '@/services/api';
import { matchDict } from '@/utils/utils';
import action from '@/utils/action';
import { socketChannel } from '@/services/socket';

export default {
  namespace: 'publicdata',
  state: {
    dictCode: {},
    areaList: [],
    custList: [],
    configList: [],
    custNsList: [],
    custAllList: [],
    supplyList: [],
    nsSupplyList: [],
    billSupplyList: [],
    sendOrderCustList: [],
    sendRecvSuppList: [],
    contList: [],
    suppContList: [],
    quoList: [],
    empNameList: [],
    empNameSelect: [],
    elementArr: [],
    matFileDictItem: [],
    downloadFile: { fileId: '', fileName: '' },
    empName: {},
    detailHdl: [],
    nameContent: null,
    nameTitle: null,
    probTypeList: [],
    alertObjList: [],
    proObjList: [],
    proListData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    serviceDictList: [],
    assoCustomerList: [],
    quoInfo: {},
    insInfo: {}, // 社保账户 单立户详情数据
    pageRatioData: {
      // 企业工伤比例列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    insBigInfo: {}, // 社保账户 大库详情数据
    accuInfo: {}, // 公积金账户 单立户详情数据
    accuBigInfo: {}, // 公积金账户 大库详情数据
    upgradeTitle: '',
    upgradeContent: '',
    injCustList: null,
    injSecAccoDetailData: {},
    injSecAccoTaxRateData: {
      list: [],
    },
    creatorList: [],
    batchTask: {},
    idCodeEmpList: [],
    empInfo: {},
    showOriginal: false, // 服务办理中是否显示选择原件下拉
    circulationRequire: false, // 服务办理中流转备注是否必填
    personList: [],
    accoOwnerList: [],
    custFsValue: {}, // 客户名称组件选择的值
    areaFsValue: {}, // 地区名称组件选择的值
    assoCustFsValue: {}, // 关联客户组件选择的值
    billSupplyFsValue: {}, // 签约方组件选择的值
    configFsValue: {}, // 配置名称组件选择的值
    contFsValue: {}, // 合同名称组件选择的值
    custNsFsValue: {}, // 全国客户名称组件选择的值
    nsSupplyFsValue: {}, // 全国供应商名称组件选择的值
    quoFsValue: {}, // 报价单名称组件选择的值
    supplyFsValue: {}, // 供应商列表组件选择的值
    suppContFsValue: {}, // 供应商合同列表组件选择的值
    sendRecvSuppFsValue: {},
    sendOrderCustFsValue: {},
  },
  effects: {
    // 查询社保公积金增减员账户负责人
    *fetchOsAccoList({ payload }, { call, put }) {
      const res = yield call(getOsAccoList, payload);
      if (res.success) {
        yield put(
          action('updateModelData', { accoOwnerList: Array.isArray(res.data) ? res.data : [] })
        );
      }
    },
    *fetchAssoCustomer({ payload }, { call, put }) {
      const res = yield call(fetchAssoCustomer, payload);
      if (res.success) {
        yield put(action('updateModelData', { assoCustomerList: res.data }));
      }
    },
    // 获取字典
    *fetchDictCode({ payload, callback }, { call, put, select }) {
      let res = null;
      if (payload[0] === 'INS_ACCU_SELF') {
        res = yield call(getDictCode, ['BIZ_INS_TYPE', 'BIZ_ACCU_TYPE']);
      } else {
        res = yield call(getDictCode, payload);
      }
      if (res.success) {
        if (payload[0] === 'INS_ACCU_SELF') {
          res.data.INS_ACCU_SELF = res.data.BIZ_INS_TYPE &&
            res.data.BIZ_ACCU_TYPE && [...res.data.BIZ_INS_TYPE, ...res.data.BIZ_ACCU_TYPE];
        }
        const dictCode = yield select(state => state.publicdata.dictCode);
        yield put(action('updateModelData', { dictCode: { ...dictCode, ...res.data } }));
        if (callback && typeof callback === 'function') {
          callback(res.data);
        }
        return res.data;
      }
    },
    // 获取模糊查询地区列表
    fetchAreaList: [
      function*({ payload: { areaName, isContainNation } }, { call, put }) {
        const res = yield call(getAreaList, { areaName });
        if (res.success && res.data && res.data.length && !isContainNation) {
          res.data = res.data.filter(item => item.areaId !== '1');
        }
        yield put(action('updateModelData', { areaList: res.data }));
      },
      { type: 'throttle', ms: 300 },
    ],
    // 获取模糊查询客户列表：有效客户
    *fetchCustList(
      {
        payload: { name, isSelfSupp = false },
      },
      { call, put, select }
    ) {
      const { suppId = null } = yield select(state => state.login.baseUser);
      const res = yield call(getCustList, isSelfSupp ? { name, suppId } : { name });
      if (res.success) {
        yield put(action('updateModelData', { custList: res.data }));
      }
    },
    // 获取模糊查询配置列表：有效配置
    *fetchConfigList({ payload }, { call, put }) {
      const res = yield call(getConfigList, { custConfName: payload });
      yield put(action('updateModelData', { configList: res.data }));
    },
    // 获取员工运行 模糊查询客户列表：有效客户
    *fetchEsOsCustList(
      {
        payload: { name, isSelfSupp = false },
      },
      { call, put, select }
    ) {
      const { suppId = null } = yield select(state => state.login.baseUser);
      const res = yield call(getCustEsOsList, isSelfSupp ? { name, suppId } : { name });
      yield put(action('updateModelData', { custList: res.data }));
    },
    // 员工系统 办理人，所属客服，创建人接口
    *fetchEsPersonList({ payload }, { call, put }) {
      const res = yield call(getEsPersonList, payload);
      if (res.success) {
        yield put(action('updateModelData', { personList: res.data }));
      }
    },
    // 获取模糊查询客户列表: 所有客户
    *fetchCustAllList({ payload }, { call, put }) {
      const res = yield call(getCustAllList, { name: payload });
      if (res.success) {
        yield put(action('updateModelData', { custAllList: res.data }));
        return res.data;
      }
    },
    // 全国供应商 - 获取模糊查询客户列表
    *fetchNsCustList({ payload }, { call, put }) {
      const res = yield call(getNsCustList, { name: payload });
      yield put(action('updateModelData', { custNsList: res.data }));
    },
    // 获取供应商列表
    *fetchSupplyList({ payload }, { call, put }) {
      const res = yield call(getSupplyList, payload);
      yield put(action('updateModelData', { supplyList: res.data }));
    },
    // NS获取供应商列表
    *fetchNsSupplyList({ payload }, { call, put }) {
      const res = yield call(getNsSupplyList, payload);
      yield put(action('updateModelData', { nsSupplyList: res.data }));
    },
    // 获取供应商帐单下的签约方:客服系统
    *fetchBillSupplyList({ payload }, { call, put }) {
      const res = yield call(getBillSupplyList, payload);
      yield put(action('updateModelData', { billSupplyList: res.data }));
    },
    // 获取客户合同名称列表
    *fetchContList({ payload }, { call, put }) {
      const res = yield call(getContList, payload);
      yield put(action('updateModelData', { contList: res.data }));
    },
    // 获取供应商合同名称列表
    *fetchSuppContList({ payload }, { call, put }) {
      const res = yield call(getSuppContList, { contName: payload });
      yield put(action('updateModelData', { suppContList: res.data }));
    },
    // 获取报价单名称列表
    *fetchQuoList({ payload }, { call, put }) {
      const res = yield call(getQuoList, { quoName: payload });
      yield put(action('updateModelData', { quoList: res.data.pageRecords }));
    },
    // ns:发单管理：客户名称
    *fetchSendOrderCustList({ payload }, { call, put }) {
      const res = yield call(getSendOrderCustList, payload);
      yield put(action('updateModelData', { sendOrderCustList: res.data }));
    },
    // ns:发单管理：接单方 或者签约方
    *fetchSendRecvSuppList({ payload }, { call, put }) {
      const res = yield call(getSendRecvSuppList, payload);
      yield put(action('updateModelData', { sendRecvSuppList: res.data }));
    },
    // 上传文件:批量
    uploadFile: [
      function*({ uploadUrl, payload, callback }, { call }) {
        const res = yield call(uploadFile, uploadUrl, payload);
        if (res.success) {
          // 上传成功
          if (callback && typeof callback === 'function') {
            callback(res.data);
          }
        } else {
          // 上传失败
          message.warning(`${res.message || '上传失败'}`);
        }
      },
      { type: 'throttle', ms: 10000 },
    ],
    // 上传文件:批量进度
    *uploadFileWithProgress({ uploadUrl, payload }, { call }) {
      const res = yield call(uploadFile, uploadUrl, payload);
      if (res.success) {
        yield call(socketChannel, {
          type: 'sub',
          data: { to: res.data && (res.data.batchId || res.data), type: 'task' },
        });
      } else {
        // 上传失败
        message.warning(`${res.message || '上传失败'}`);
      }
      return res;
    },
    // 获取模糊查询员工姓名列表
    *fetchEmpNameList({ payload }, { call, put }) {
      const res = yield call(getEmpNameList, payload);
      yield put(action('updateModelData', { empNameList: res.data }));
    },

    // 证件号查询员工：姓名，客户
    *searchIdCodeEmpList(
      {
        payload: { searchUrl, params },
      },
      { call, put }
    ) {
      const res = yield call(getIdCodeEmpList, searchUrl, params);
      if (res.success && res.data) {
        if (!res.data.length) {
          return message.warning('没有查询到该雇员下的信息！');
        }
        yield put(action('updateModelData', { idCodeEmpList: res.data }));
      } else {
        return message.warning(res.message || '服务器异常');
      }
    },
    *serviceType({ payload }, { call, put }) {
      const res = yield call(getServiceType, payload);
      if (res.success) {
        yield put(action('updateModelData', { serviceTypeList: res.data }));
      }
    },
    // 获取模版文件id与名称
    *fetchFileName({ payload }, { call, put }) {
      const res = yield call(getFileName, payload);
      yield put(action('updateModelData', { fileName: res.data }));
    },
    // 获取问题人员类型
    *fetchProType({ payload }, { call, put }) {
      const res = yield call(getProType, payload);
      if (res.success) {
        yield put(action('updateModelData', { probTypeList: res.data }));
      }
    },
    // 获取提醒对象
    *fetchAlertList({ payload }, { call, put }) {
      const res = yield call(getDictCode, payload);
      if (res.success) {
        const tempArr = [];
        res.data.ALRT_OBJ.map(item => {
          tempArr.push({ label: item.itemName, value: item.itemCode });
        });
        yield put(action('updateModelData', { alertObjList: tempArr }));
      }
    },
    // 获取问题对象
    *fetchProObjList({ payload }, { call, put }) {
      const res = yield call(getDictCode, payload);
      if (res.success) {
        const tempArr = [];
        const listArr = [...res.data.BIZ_INS_TYPE, ...res.data.BIZ_ACCU_TYPE];
        listArr.map(item => {
          tempArr.push({ label: item.itemName, value: item.itemCode });
        });
        yield put(action('updateModelData', { proObjList: tempArr }));
      }
    },
    // 标记问题人员
    *signPro({ payload, callback }, { call }) {
      const res = yield call(signPro, payload);
      if (callback) {
        callback(res);
      }
    },
    // 获取问题人员列表
    *fetchProList({ payload }, { call, put }) {
      const res = yield call(getProList, payload);
      const {
        pagerArg: { currentPage, pageSize },
      } = payload;
      if (res.success) {
        const proListData = {
          list: res.data.pageRecords,
          pagination: { total: res.data.totalCount, current: currentPage, pageSize },
        };
        yield put(action('updateModelData', { proListData }));
      }
    },

    // 查询服务类型列表
    *fetchServiceDictList({ payload }, { call, put }) {
      const res = yield call(getServiceDictList, payload);
      if (res.success) {
        yield put(action('updateModelData', { serviceDictList: res.data }));
      }
    },
    // 获取报价单信息
    *fetchQuoInfo({ payload }, { call, put, select }) {
      const res = yield call(getQuoInfo, payload);
      const dictCode = yield select(state => state.publicdata.dictCode);
      yield put(action('updateModelData', { quoInfo: {} }));
      if (res.success && res.data) {
        const detailInfo = res.data;
        if (detailInfo.packList.length) {
          detailInfo.packList.map(pack => {
            if (pack.listQuoPd.length) {
              pack.listQuoPd.map(pd => {
                if (pd.listAttr.length) {
                  pd.listAttr.map(attr => {
                    attr.attrValName = [];
                    attr.name = '';
                    if (attr.attrValList.length) {
                      attr.attrValList.forEach(item => {
                        attr.attrValName.push(matchDict(dictCode[attr.dictType], item));
                      });
                      attr.name = attr.attrValName.join(',');
                    }
                  });
                }
              });
            }
          });
        }
        yield put(action('updateModelData', { quoInfo: detailInfo }));
      }
      return res;
    },
    // 获取社保账户信息 单立户
    *fetchInsDetailInfo({ payload }, { call, put }) {
      const res = yield call(getInsDetailInfo, payload);
      yield put(action('updateModelData', { insInfo: {} }));
      if (res.success && res.data) {
        const detailInfo = res.data;
        yield put(action('updateModelData', { insInfo: detailInfo }));
      }
      return res;
    },
    // 社保账户信息 单立户 企业工伤比例
    *fetchInjRatioPage({ payload }, { call, put }) {
      const res = yield call(fetchInjRatioPage, payload);
      const {
        pageArg: { currentPage, pageSizes },
      } = payload;
      if (res.success) {
        const pageRatioData = {
          list: res.data.pageRecords,
          pagination: { total: res.data.totalCount, current: currentPage, pageSize: pageSizes },
        };
        yield put(action('updateModelData', { pageRatioData }));
      }
    },
    // 获取社保账户信息 大库
    *fetchDetailInforPage({ payload }, { call, put }) {
      const res = yield call(getDetailInforPage, payload);
      if (res.success && res.data) {
        yield put(action('updateModelData', { insBigInfo: res.data }));
      }
      return res;
    },
    // 获取公积金账户信息 单立户
    *fetchAccuDetailInfo({ payload }, { call, put }) {
      const res = yield call(getAccuDetailInfo, payload);
      if (res.success && res.data) {
        yield put(action('updateModelData', { accuInfo: res.data }));
      }
      return res;
    },
    // 获取公积金账户信息 大库
    *fetchDetailAccuInforPage({ payload }, { call, put }) {
      const res = yield call(getDetailAccuPage, payload);
      if (res.success && res.data) {
        yield put(action('updateModelData', { accuBigInfo: res.data }));
      }
      return res;
    },

    // 获取缴费人员类别
    *getJoinIde({ payload }, { call }) {
      const res = yield call(getJoinIdeList, payload);
      return res;
    },

    // 获取社保政策详情
    *getInsDetail({ payload }, { call }) {
      const res = yield call(getInsDetailData, payload);
      return res;
    },

    // 获取险种下的详情
    *getPdIdDetail({ payload }, { call }) {
      const res = yield call(getPdIdDetailData, payload);
      return res;
    },

    // 获取公积金政策详情
    *getAccuDetail({ payload }, { call }) {
      const res = yield call(getAccuDetailData, payload);
      return res;
    },

    // 获取公积金组合详情
    *getAccuLsPkgDetail({ payload }, { call }) {
      const res = yield call(getAccuLsPkgDetailData, payload);
      return res;
    },

    // 获取工伤二级户弹框详情
    *fetchInjSecAccoDetail({ payload }, { call, put }) {
      const res = yield call(getInjSecAccoDetailData, payload);
      if (res.success) {
        const tempArr = [];
        let custNameList = {};
        // eslint-disable-next-line no-unused-expressions
        res.data.custList &&
          res.data.custList.forEach(item => {
            tempArr.push(item.mdCustName);
          });
        custNameList = Object.assign(custNameList, {
          custList: tempArr.join(','),
        });
        yield put(
          action('updateModelData', {
            injSecAccoDetailData: res.data.injSecAcco || {},
            injCustList: custNameList.custList || null,
            injSecAccoTaxRateData: {
              list: res.data.ratioList || [],
            },
          })
        );
      }
    },
    // 获取模糊查询客户列表：员工系统一次性费用新增客户
    *fetchEsOnceCustList(
      {
        payload: { name, isSelfSupp = false },
      },
      { call, put, select }
    ) {
      const { suppId = null } = yield select(state => state.login.baseUser);
      const res = yield call(getEsOnceCustList, isSelfSupp ? { name, suppId } : { name });
      if (res.success) {
        yield put(action('updateModelData', { custList: res.data }));
      }
    },
  },
  reducers: {
    // 当前state数据写入
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    getAreaList(state, { payload }) {
      return {
        ...state,
        areaList: payload,
      };
    },
    getCustList(state, { payload }) {
      return {
        ...state,
        custList: payload,
      };
    },
    getNsCustList(state, { payload }) {
      return {
        ...state,
        custNsList: payload,
      };
    },
    fetchEmpName(state, { payload }) {
      return {
        ...state,
        empNameList: payload,
      };
    },
    // 设置下载文件模板信息
    setFileDownload(state, { payload }) {
      return {
        ...state,
        downloadFile: payload,
      };
    },
    // 系统升级标题和内容
    updateUpgrade(state, { payload }) {
      return {
        ...state,
        upgradeTitle: payload.title,
        upgradeContent: payload.content,
      };
    },
    // 设置批量任务数据：全局
    updateBatchTaskData(state, { payload = { batchId: null } }) {
      const { batchTask } = state;
      return {
        ...state,
        batchTask: { ...batchTask, [payload.batchId]: payload },
      };
    },
    /**
     * 清除Customer组件共享数据
     */
    clearCustomerComponentData(state) {
      return {
        ...state,
        custList: [],
        custFsValue: {},
      };
    },
    setCustFsValue(state, { payload }) {
      return {
        ...state,
        custFsValue: payload.custFsValue,
      };
    },
  },
};
